// request.js
import axios from 'axios';
import { useTokenStore } from '@/store/tokenStore';

// 设置基础URL
axios.defaults.baseURL = 'http://localhost:8090';

const request = axios.create();

// 请求拦截器
request.interceptors.request.use(config => {
    const tokenStore = useTokenStore();
    const token = tokenStore.accessToken;
    if (config.url !== '/login' && config.url !== '/logout') {
        config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
}, error => Promise.reject(error));

// 响应拦截器
request.interceptors.response.use(
    response => {
        const tokenStore = useTokenStore();
        // 如果是登录响应，则设置 token
        console.log(response.config.url)
        if (response.config.url === 'login' && response.data.success) {
            tokenStore.setAccessToken(response.data.data.accessToken);
            tokenStore.setRefreshToken(response.data.data.refreshToken);
        }

        return response.data;
    },
    async error => {
        const originalRequest = error.config;
        const tokenStore = useTokenStore();
        if (error.response.status === 401 && !originalRequest._retry) {
            originalRequest._retry = true;

            try {
                const refreshToken = tokenStore.refreshToken;
                const refreshResponse = await axios.post('/refresh-token', {refresh_token: refreshToken});

                if (refreshResponse.data.success) {
                    tokenStore.setAccessToken(refreshResponse.data.data.accessToken);
                    tokenStore.setRefreshToken(refreshResponse.data.data.refreshToken);
                    return request(originalRequest);
                }
            } catch (err) {
                console.error('Token refreshing failed:', err);
            }
        }

        return Promise.reject(error);
    }
);

export default request;
